package com.psa.system;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import com.psa.dialog.SearchCustomerDialog;
import com.psa.element.Customer;
import com.psa.element.District;
import com.psa.element.ISqlObject;
import com.psa.tool.*;
import com.wxw.BaseLibrary.adapter.ObjectListAdapter;
import com.wxw.BaseLibrary.tool.ActivityTool;
import com.wxw.BaseLibrary.tool.L;
import net.duohuo.dhroid.ioc.InjectUtil;
import net.duohuo.dhroid.ioc.annotation.InjectView;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author david
 * @date 2014/5/13
 */
public class DistrictsActivity extends BaseActivity {
    @InjectView(id = R.id.district_list)
    private ListView district_list;
    @InjectView(id = R.id.btn_back, click = "onClick")
    private Button back_button;
    @InjectView(id = R.id.search_customer, click = "onClick")
    private Button search_customer;
    @InjectView(id = R.id.btn_next)
    private Button btn_next;
    private List<Object> districts = new ArrayList<Object>();
    private boolean isback = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityTool.hideTitle(this);
        ActivityTool.fullScreen(this);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.districtlist);
        InjectUtil.inject(this);
        district_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                openDistrictCustomer(i);
            }
        });
        tv_head_title.setText(getString(R.string.district_title));
        back_button.setText(getString(R.string.customer_manager_code_btn_back));
        btn_next.setVisibility(View.INVISIBLE);

        refreshDistricts();
        ObjectListAdapter adapter = new ObjectListAdapter(this, districts);
        adapter.setHasShadow(true);
        adapter.setFontSize(20);
        adapter.setVerticalMargin(20);
        district_list.setAdapter(adapter);
        tv_info.setText(SystemStatus.getReqCount());
        if (districts.size()==1){
            if (isback){
                setResult(0);
                finish();
            } else {
                openDistrictCustomer(0);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 0:
                if (districts.size()==1) {
                    setResult(0);
                    finish();
                }
                SystemStatus.currentCustomer = null;
                break;
            case 1:
                if (resultCode == 1){
                    DistrictsActivity.this.startActivityForResult(new Intent(DistrictsActivity.this, CustomerActivity.class), 0);
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK){
//            RequestManager.getRequestManager().removeGeneralEventListener(this);
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.search_customer) {
            SearchCustomerDialog dialog = new SearchCustomerDialog(this);
            dialog.setOnCustomerSearchedListener(new SearchCustomerDialog.OnCustomerSearchedListener() {
                @Override
                public void onSearched(Object o, Customer customer) {
                    SystemStatus.currentCustomer = customer;
                    DistrictsActivity.this.startActivityForResult(new Intent(DistrictsActivity.this, CustomerVisitActivity.class), 0);
                }
            });
            dialog.show();
        } else {
            super.onClick(view);
        }
    }

    private void refreshDistricts(){
        try {
            //Cursor cursor = DBTool.getInstance().query("Select A.ID,A.ChineseName,A.EnglishName,A.Routine From (Select Distinct DistrictID From OperatorCustomer Where Weekday=" + ToolsDate.getWeekDayIndex() + " Or Weekday=-1) B Left Join District A On LTRIM(RTRIM(A.ID))=B.DistrictID");
            //Cursor cursor = DBTool.getInstance().query("Select A.ID,A.ChineseName,A.EnglishName,A.Routine From District A Left Join (Select Distinct DistrictID From OperatorCustomer Where Weekday=" + ToolsDate.getWeekDayIndex() + ") B On LTRIM(RTRIM(A.ID))=B.DistrictID");
            if (DBTool.getInstance() == null) {
                return;
            }
            Cursor cursor = DBTool.getInstance().query("Select Distinct DistrictID as ID,DistrictID as ChineseName,'' as EnglishName,'' as Routine From OperatorCustomer Where Weekday=" + ToolsDate.getWeekDayIndex() );//+ ToolsDate.getWeekDayIndex()
            ISqlObject district = new District();
            districts.clear();
            while ((district = district.full(cursor)) != null) {
                if (((District)district).ID!=null && ((District)district).ChineseName!=null) {
                    districts.add(district);
                }
            }
            if (cursor != null) {
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(SystemStatus.TAG, e.getMessage());
            L.WriteExceptionLog("DistrictsActivity", "refreshDistricts", e.getMessage());
//            SystemStatus.showMessage(e.getMessage());
        }
    }

    private void openDistrictCustomer(int i){
        ((ObjectListAdapter)district_list.getAdapter()).setIndex(i);
        SystemStatus.currentDistrict = (District)districts.get(i);
        RequestManager.getRequestManager().removeGeneralEventListener(DistrictsActivity.this);
        DistrictsActivity.this.startActivityForResult(new Intent(DistrictsActivity.this, DistrictCustomerActivity.class), 0);
    }

    @Override
    public void finished(Object sender, String eventContent) {
        if (sender instanceof RequestManager){
            DistrictsActivity.this.runOnUiThread(showRequestChangedCallback);
        } else {

        }
    }
}
